package top.infopub.mgr.hr.web;


import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.hr.service.DeptInfoService;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.PostInfoService;
import top.infopub.mgr.hr.vo.DeptInfoVo;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.DeptInfo;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.PostInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.tdp.util.GrpParaUtil;
import top.infopub.util.IdFactory;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.Page;
import com.google.common.collect.Maps;


/**
 * 部门管理
 * @author wangw
 * @version 2020年1月2日
 * @see DeptInfoController
 * @since
 */
@Controller
@RequestMapping("/dept")
public class DeptInfoController extends GenericController {

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private PostInfoService postInfoService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 部门列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = "";
        //String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if (StringUtils.isEmpty(visibleOrgIds)) {
            Map<String, Object> where = Maps.newHashMap();
            where.put("state", 1);
            where.put("orderCondition", " types asc, add_time asc");
            orgInfos = orgInfoService.selectByMapWhere(where);
        }
        else {
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "hr/lay-deptInfo-list";
    }

    /**
     * 部门列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<DeptInfoVo> queryDataByCondition(DeptInfoVo deptInfoVo, ParamPage paramPage) {
        Page<DeptInfoVo> page = new Page<DeptInfoVo>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if (StringUtils.isEmpty(deptInfoVo.getOrgId())) {
            Object tmp = SessionUserUtils.getSessionAttribute("bindOrgId");
            // 为空默认显示 总部
            if (tmp == null) {
                deptInfoVo.setOrgId((String)SessionUserUtils.getSessionAttribute("superOrgId"));
            }
            else {
                deptInfoVo.setOrgId((String)tmp);
            }
        }
        page = deptInfoService.selectPageByDomainWhere(page, deptInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 首页工作台-根据id查询部门详情
     * @param id 部门Id
     * @return
     * @see
     */
    @RequestMapping("/queryById")
    public @ResponseBody ModelAndView queryById(HttpServletRequest request) {
        //String id = request.getParameter("id");
        Map<String, Object> map = new HashMap<String, Object>();
        //DeptInfoVo deptInfo = deptInfoService.selectById(id);
        //map.put("deptInfo", deptInfo);
        return new ModelAndView("hr/lay-deptInfo-detail", map);
    }

    /**
     * 根据公司查找（一级、二级）部门
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getDeptByOrgId")
    @ResponseBody
    public Map<String, Object> getDeptByOrgId(String orgId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<DeptInfo> deptInfos = deptInfoService.selectByOrgId(orgId);
            map.put("depts", deptInfos);
        }
        catch (Exception e) {
            log.error("根据类型查找公司异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据公司查找所有部门
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getAllDeptByOrgId")
    @ResponseBody
    public Map<String, Object> getAllDeptByOrgId(String orgId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<DeptInfo> deptInfos = deptInfoService.selectAllByOrgId(orgId);
            map.put("depts", deptInfos);
        }
        catch (Exception e) {
            log.error("根据类型查找公司异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据部门查询岗位
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getPostByDeptId")
    @ResponseBody
    public Map<String, Object> getPostByDeptId(String deptId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<PostInfo> postInfos = postInfoService.getPostByDeptId(deptId);
            map.put("posts", postInfos);
        }
        catch (Exception e) {
            log.error("根据类型查找公司异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 新增/编辑部门
     * @param deptInfoVo
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/save")
    public @ResponseBody RspVo<DeptInfoVo> save(DeptInfoVo deptInfoVo) {
        if (StringUtils.isEmpty(deptInfoVo.getDeptName())
            || StringUtils.isEmpty(deptInfoVo.getDeptLeader())
            || StringUtils.isEmpty(deptInfoVo.getOrgId())) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        String deptId = StringUtils.EMPTY;
        boolean flag = true;
        if (StringUtils.isEmpty(deptInfoVo.getId())) {
            DeptInfo deptInfoWhere = new DeptInfo();
            deptInfoWhere.setDeptName(deptInfoVo.getDeptName());
            deptInfoWhere.setOrgId(deptInfoVo.getOrgId());
            deptInfoWhere.setState(1);
            List<DeptInfo> deptInfos = deptInfoService.selectByEntityWhere(deptInfoWhere);
            if(CollectionUtils.isNotEmpty(deptInfos)){
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("部门名称【"+deptInfoVo.getDeptName()+"】已经存在~");
            }
            deptId = IdFactory.getUUIDUpper();
            deptInfoVo.setId(deptId);
            String deptCode = codeGeneratorConfigService.generatorCode("hr_dept_info");
            deptInfoVo.setDeptCode(deptCode);
        }
        else {
            List<DeptInfo> deptInfos = deptInfoService.selectByDeptNameAndId(deptInfoVo.getDeptName(),deptInfoVo.getId(),deptInfoVo.getOrgId());
            if(CollectionUtils.isNotEmpty(deptInfos)){
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("部门名称【"+deptInfoVo.getDeptName()+"】已经存在~");
            }
            deptId = deptInfoVo.getId();
            flag = false;
        }
        deptInfoService.saveDeptInfo(deptInfoVo, flag);
        if (flag) {
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.ADD, "新增部门 - 部门名称:"
                                                                + deptInfoVo.getDeptName().trim(),
                null);
        }
        else {
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE,
                "修改部门 - 部门Id:" + deptInfoVo.getId(), null);
        }
        return RspVo.getSuccessResponse(deptInfoVo);
    }

    /**
     * 修改部门状态
     * @param operatorVo
     * @return
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(DeptInfo deptInfo) {
        DeptInfo dept = deptInfoService.selectByPrimaryKey(deptInfo.getId());
        Integer oldStatus = dept.getState();
        Integer newStatus = 0;
        if (oldStatus == 0) {
            newStatus = 1;
        }
        else {
            newStatus = 0;
        }
        dept.setState(newStatus);
        dept.setUptTime(new Date());
        dept.setUptBy(SessionUserUtils.getSessionUserId());
        deptInfoService.updateBySelective(dept);
        // 操作日志
        LogUtil.bizLog(
            LogUtil.LogModelType.OTHER,
            LogUtil.AcctionType.UPDATE,
            "修改状态  部门名称:" + dept.getDeptName() + " 原状态:"
                + GrpParaUtil.getName("A00010020", String.valueOf(oldStatus)) + " 被修改为:"
                + GrpParaUtil.getName("A00010020", String.valueOf(newStatus)), "");
        return RspVo.getSuccessResponse();
    }
}
